from django.core.paginator import Paginator
from django.http import HttpResponseNotFound
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU
from apps.goods.utils import get_breadcrumb

#商品详情页
class DetailView(View):
    def get(self,request,sku_id):
        #商品分类
        categories = get_categories()

        #sku对象
        sku = SKU.objects.get(id = sku_id)

        #面包屑组件
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs':goods_specs,
        }
        return render(request,'detail.html',context=context)

#热销商品
class HotGoodsView(View):
    def get(self,request,category_id):
        skus = SKU.objects.filter(category_id = category_id,is_launched=True).order_by('-sales')[:2]

        #序列化
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image_url':sku.default_image.url,
                'name':sku.name,
                'price':sku.price,
            })
        return JsonResponse({'code':0,'errmsg':'OK','hot_skus':hot_skus})

#商品列表页
class ListView(View):
    def get(self,request,category_id,page_num):
        #获取三级分类对象
        try:
            category = GoodsCategory.objects.get(id = category_id)
        except Exception as e:
            return HttpResponse('商品不存在')

        #接收查询参数
        sort = request.GET.get('sort','default')

        #商品分类数据
        categories = get_categories()

        #面包屑组件
        breadcrumb = get_breadcrumb(category)

        #判断排序规则
        if sort == "price":
            #价格由低到高
            sort_field = 'price'
        elif sort == 'hot':
            #销量由高到低
            sort_field = '-sales'
        else:
            #默认按照创建时间排序
            sort_field = 'create_time'
        #按照规则取出对应的商品
        skus = SKU.objects.filter(category = category,is_launched=True).order_by(sort_field)

        #创建分页器 参数1：需要显示的商品  参数2：每页显示的个数
        paginator = Paginator(skus,5)
        #获取每页商品数据
        try:
            page_skus = paginator.page(page_num)
        except Exception as e:
            return HttpResponseNotFound('empty page')
        #获取列表页总页数
        total_page = paginator.num_pages


        #返回数据
        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sort':sort,
            'category':category,
            'page_skus':page_skus,
            'total_page':total_page,
            'page_num':page_num,
        }
        return render(request,'list.html',context)
